package main

import (
	"bufio"
	"fmt"
	"strconv"
	"tran_util/util"
	"unicode/utf8"

	//ydfanyi "github.com/hnmaonanbei/go-youdao-fanyi"
	"os"
	//"github.com/mind1949/googletrans"

	//"github.com/pkg/errors"
)

func HandleTran(w string,limit int) {
	//opts := ydfanyi.NewOptions("", "", "")
	// opts.proxy = ""
	//opts.From = ydfanyi.EN
	//opts.To = ydfanyi.ZH
	var err error = nil
	//var res string
	//res = w
	//res, err := ydfanyi.Do(w, opts)
	if err!=nil {
		fmt.Printf("网络问题,请重试：-> %v",err)
	}
	// 翻译结果
	word, err := util.ParseWord(w, limit)
	if err!=nil {
		fmt.Printf("出现问题，请重试 %v\n",err)
		return
	}
	fmt.Println(word.Word)
	fmt.Println(word.Type)
	//fmt.Println(word.Explain)
	for _,v := range word.Type {
		fmt.Println(v)
	}
	fmt.Println()
	for _,v := range word.SentenceExample {
		fmt.Println(v.ExampleSentence)
		fmt.Println(v.ExampleExplain)
		fmt.Println()
	}
	fmt.Printf("\r\n---------------\r\n\r\n")

	//fmt.Println(word.SentenceExample)
	//fmt.Println(res)
	// 详细信息
	//fmt.Println(res.SmartResult.Entries)
	// out
}

func HandleConsoleRead(reader *bufio.Reader) (string,error) {
	fmt.Printf("translate: <- ")
	line ,_,err := reader.ReadLine()
	if err != nil {
		return "",err
	}
	res := string(line)
	return res, nil

	//return "",errors.New("quit...")
}




func main() {
	var limit int

	args := os.Args
	if len(args) >=2 {
		res := args[1]
		//fmt.Println("args : = ",args)
		if res == "-h" {
			fmt.Println("第二个参数表示 返回的句子")
			fmt.Println("输入 t 表示 翻译句子模式")
			return
		}
		atoi, err := strconv.Atoi(res)
		if err!=nil || atoi<=0 {
			atoi = 3
		}
		limit = atoi

	}
	reader := bufio.NewReader(os.Stdin)
	for {
		s,err := HandleConsoleRead(reader)
		if err != nil {
			fmt.Printf("error occur ... %v", err)
			break
		}
		slen := len(s)
		if slen == 5 && ( s == "-quit" || s == "-exit")  {
			fmt.Printf("type 1 and quit... :<- ")
			line, _, _ := reader.ReadLine()
			w := string(line)
			if w == "1" {
				break
			}
		}
		chCnt := utf8.RuneCountInString(s)
		if chCnt>0 && chCnt <= 10 {
			HandleTran(s,limit)
		}else if chCnt >10 {
			//fmt.Println(chCnt)
			res ,_ := util.ParseSentence(s)
			fmt.Printf("\n\n%s\n---------\n",res)
		} else if slen == 0 {
			fmt.Println("empty strings")
		}

	}


}
